package com.tdcy.framework.util;

import java.lang.reflect.Method;


/**
 * <p>XML工具类</p>
 * <p><b>最后修改时间：</b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2010-12-17下午02:37:37</p>
 * @author zhengwei.bu
 * @version 1.0
 */
public class XmlUtils {
	
	public static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	
	private static String createRootNode(String className) {
		int ind = className.lastIndexOf('.');
		String tmp = className.substring(ind + 1);
		
		return tmp.substring(0, 1).toLowerCase() + tmp.substring(1);
	}
	
	private static String createNode(String methodName) {
		String tmp = methodName.substring(3);
		
		return tmp.substring(0, 1).toLowerCase() + tmp.substring(1);
	}
	
	/**
	 * Just for String as the parameter
	 */
	public static String convertObjToXml(Object obj) {
		Class<?> clazz = obj.getClass();
		Method[] methods = clazz.getMethods();
		
		StringBuffer xml = new StringBuffer();
		String root = createRootNode(clazz.getName());
		xml.append("<" + root + ">");
		String methodName = "";
		for (Method method : methods) {
			methodName = method.getName();
			if (methodName.startsWith("get") && method.getReturnType().equals(String.class)) {
				xml.append("<" + createNode(methodName) + ">");
				try {
					xml.append((String) method.invoke(obj));
				} catch (Exception e) {
					// Nothing to do
				}
				xml.append("</" + createNode(methodName) + ">");
			}
		}
		xml.append("</" + root + ">");
		
		return xml.toString();
	}
	
}
